package com.app.baselibrary.http

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLEngine
import javax.net.ssl.X509TrustManager

/**
 * ssl 加密传输工具类
 */
object SSLUtil {

    /**
     * 构建SSLContext
     */
    @Synchronized
    fun createSSLContext(): SSLContext {
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, arrayOf(object : X509TrustManager{
            override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {}

            override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {}

            override fun getAcceptedIssuers(): Array<X509Certificate> {
                return arrayOf()
            }

        }), SecureRandom())
        return sslContext
    }


    /**
     * 构建sslEngine
     */
    fun buildSSLEngine(): SSLEngine{
        return createSSLContext().createSSLEngine().apply {
            //启用客户端模式
            useClientMode = true
        }
    }
}